#!/usr/bin/python
# -*- coding: UTF-8 -*-
import tensorflow as tf
import os
import argparse

parse=argparse.ArgumentParser(description="线性回归模型")
parse.add_argument("step",type=int,default=100)
parse.add_argument("model_dir",type=str)
args=parse.parse_args()

def myregreession():
    '''
    自实现一个线性回归
    1. 变量能够持久化保存
    2. 定一个变量op的时候一定要在会话中初始化
    3. 使用变量才能优化
    :return:
    '''

    with tf.variable_scope("data"):
        x=tf.random_normal([100,1],mean=1.75,stddev=0.5,name="x_data")

        y_true=tf.matmul(x,[[0.7]])+0.8

    with tf.variable_scope("model"):
        weight=tf.Variable(tf.random_normal([1,1],0,1.0),name="w")#trainable=fales 禁止优化
        bias=tf.Variable(0.0,"b")
        y_prodict=tf.matmul(x,weight)+bias
    with tf.variable_scope("loss"):
        loss = tf.reduce_mean(tf.square(y_true-y_prodict))

    with tf.variable_scope("optimizer"):
        aaa_op=tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    tf.summary.scalar("losses",loss) # 收集损失
    tf.summary.histogram("weights",weight) # 收集权重

    merged = tf.summary.merge_all()
    v_init=tf.global_variables_initializer() # 必须显示的初始化

    ### 定义一个保存模型的实例
    saver=tf.train.Saver()

    with tf.Session() as sess:
        sess.run(v_init) # 运行变量的初始化

        print("随机初始化的权重为{},偏置为{}".format(weight.eval(),bias.eval()))
        fileWrite= tf.summary.FileWriter('./tmp/summary/test',graph=sess.graph)


        ## 加载模型
        if os.path.exists("./tmp/ckpt/checkpoint"):
            saver.restore(sess,args.model_dir)
            pass

        for i in range(args.step):
            sess.run(aaa_op)
            summary=sess.run(merged)
            fileWrite.add_summary(summary,i)
            print("第{}次优化的权重为{},偏置为{}".format(i,weight.eval(), bias.eval()))
        saver.save(sess,args.model_dir)
    pass


if __name__ == '__main__':
    myregreession()